<?php

namespace Plugins\AdminBasic\Http\Admin\Service;

use App\Http\OperationLogService;
use App\Interfaces\RequestLogInterface;
use App\Util\Helper;
use Sc\Util\ImitateAopProxy\AopProxyTrait;
use App\Http\Admin\Service\Traits\DestroyServiceTrait;
use App\Http\Admin\Service\Traits\StoreServiceTrait;
use App\Http\Admin\Service\Traits\SwitchServiceTrait;
use App\Http\Admin\Service\Traits\UpdateServiceTrait;
use App\Util\EasySearch;
use Plugins\AdminBasic\Models\BasicOperationLogs;


/**
 * 操作日志
 */
class OperationLogsService implements RequestLogInterface
{

    use AopProxyTrait;
    use StoreServiceTrait;
    use UpdateServiceTrait;
    use DestroyServiceTrait;
    use SwitchServiceTrait;

    /**
     * 获取模型
     */
    public function getModel(int $id = null): BasicOperationLogs
    {
        return $id ? BasicOperationLogs::find($id) :new BasicOperationLogs();
    }

    /**
     * 获取列表
     */
    public function lists(): array
    {
        $query = BasicOperationLogs::select([
            'id',
            'request_id',
            'module',
            'method',
            'url',
            'des',
            'create_time',
        ])->orderByDesc('id');

        return EasySearch::create($query)->getData();
    }

    public function cacheRouteDes(): void
    {
        OperationLogService::updateCacheMap();
    }

    public function save(string $des, array $data, string $model = '', int $userId = 0, ?array $userInfo = [], ?array $sqls = [], array $exception = []): void
    {
        $operationLogs = new BasicOperationLogs();

        foreach ($data as $key => &$value) {
            if (str_contains($key, 'password') || str_contains($key, 'pwd')) {
                $value = "****";
            }elseif (str_contains($key, 'phone')){
                $value = substr_replace($value, '****', 3, 4);
            }elseif (str_contains($key, 'id_card') || str_contains($key, 'bank_card')){
                $value = substr_replace($value, '****', 8, 4);
            }
        }

        $operationLogs->method     = Helper::request()->getMethod();
        $operationLogs->data       = $data;
        $operationLogs->query      = Helper::request()->getQueryString() ?: '';
        $operationLogs->url        = Helper::request()->url();
        $operationLogs->user_model = $model;
        $operationLogs->user_id    = $userId;
        $operationLogs->des        = $des;
        $operationLogs->user_info  = $userInfo;
        $operationLogs->module     = Helper::getModule();
        $operationLogs->ip         = Helper::getIp();
        $operationLogs->sql        = $sqls;
        $operationLogs->exception  = $exception;
        $operationLogs->request_id = Helper::getRequestId();

        $operationLogs->save();
    }
}